package mall.demo.crawl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import mall.demo.mybatis.pojo.Product;
import mall.demo.util.CrawlType;

public class DdSearchCrawler implements ICrawler {
	private static String ddPrefix = "http://search.dangdang.com/?";
	private static Logger logger = LoggerFactory.getLogger(DdSearchCrawler.class);
	
	private String key;

	public DdSearchCrawler(String key) {
		// TODO Auto-generated constructor stub
		this.key = key;
	}

	@Override
	public void setProperties(Properties prop) {
		// TODO Auto-generated method stub

	}

	@Override
	public List<Product> crawl() {
		// TODO Auto-generated method stub
		if (this.key == null || this.key.trim().equals("")) {
			return new ArrayList<Product>();
		}
		List<Product> list = new ArrayList<Product>();
		String url = ddPrefix + "key=" + this.key;
		try {
			Document doc = Jsoup.connect(url).get();
			Elements elements = doc.select("div#search_nature_rg ul.bigimg li");
			Iterator<Element> it = elements.iterator();
			while(it.hasNext()) {
				try {
					Element element = it.next();
					String code = CrawlType.getProductCodeByType(CrawlType.DDSEARCH);
					String name = element.select("p.name a").text();
					String link = element.select("p.name a").attr("href");
					String desc = element.select("p.detail").text();
					if(desc == null || desc.trim().equals("")) {
						desc = name + " 来自 " + CrawlType.DDSEARCH + " 可见" + link;
					}
					String price = element.select("p.price span.search_now_price").text();
					if(price == null || price.equals("")) {
						price = element.select("p.price span.price_n").text();
						if(price == null || price.equals("")) {
							String raw = element.select("p.price").html();
							logger.info("no price detect. see this " + raw);
							continue;
						}
					}
					logger.info("price=" + price);
					try {
						Double.parseDouble(price);
					} catch(Exception e) {
						price = price.substring(1);//rmb single
					}
					Product p = new Product();
					p.setCode(code);
					p.setName(name);
					p.setDescription(desc);
					p.setPrice(Double.parseDouble(price));
					list.add(p);	
				} catch(Exception e) {
					logger.error(e.getMessage(), e);
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
					
		return list;
	}

}
